package com.fujimana.rockincat.restree.filter;

import java.io.IOException;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class DelegateFilter implements Filter {

	private String before;

	private String after;

	private String urlPattern;

	private Filter filter;

	public DelegateFilter(Filter filter, String urlPattern, String before,
			String after) {
		this.before = before;
		this.after = after;
		this.urlPattern = urlPattern;
		this.filter = filter;
	}

	@Override
	public void destroy() {
		this.filter.destroy();
	}

	public String getBefore() {
		return before;
	}

	public String getAfter() {
		return after;
	}
	
	private boolean isMatch(String path, String urlPattern) {
		
		if(path.equals(urlPattern)) {
			return true;
		}
		
		if(Pattern.compile(urlPattern).matcher(path).find()) {
			return true;
		}
		
		return false;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		String path = ((HttpServletRequest)request).getServletPath();
		
		if(isMatch(path, urlPattern)) {
			this.filter.doFilter(request, response, chain);
		} else {
			chain.doFilter(request, response);
		}
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		this.filter.init(config);
	}

}
